<template>
  <a-modal
    :title="title"
    :width="600"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="取消"
  >
    <a-spin :spinning="confirmLoading">
      <a-form-model ref="form" :model="model" :rules="validatorRules" :label-col="labelCol" :wrapper-col="wrapperCol">
        <!-- 库存基本信息 -->
        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-model-item label="订单号">
              <a-input v-model="inventoryInfo.orderNo" :readOnly="true" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="门窗窗号">
              <a-input v-model="inventoryInfo.windowNo" :readOnly="true" />
            </a-form-model-item>
          </a-col>
        </a-row>

        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-model-item label="仓库/库位">
              <a-input :value="`${inventoryInfo.warehouseName}/${inventoryInfo.locationName}`" :readOnly="true" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="当前可用数量">
              <a-input-number v-model="inventoryInfo.availableQuantity" :readOnly="true" style="width: 100%" />
            </a-form-model-item>
          </a-col>
        </a-row>

        <a-divider>调整信息</a-divider>

        <!-- 调整信息 -->
        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-model-item label="调整类型" prop="adjustType">
              <a-select v-model="model.adjustType" placeholder="请选择调整类型" @change="handleAdjustTypeChange">
                <a-select-option :value="1">增加库存</a-select-option>
                <a-select-option :value="2">减少库存</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="调整数量" prop="adjustQuantity">
              <a-input-number
                v-model="model.adjustQuantity"
                :min="1"
                :max="maxAdjustQuantity"
                placeholder="请输入调整数量"
                style="width: 100%"
                @change="calculateAfterQuantity"
              />
            </a-form-model-item>
          </a-col>
        </a-row>

        <a-row :gutter="24">
          <a-col :span="24">
            <a-form-model-item label="调整原因" prop="adjustReason">
              <a-textarea v-model="model.adjustReason" placeholder="请输入调整原因" :rows="3" :maxLength="200" />
            </a-form-model-item>
          </a-col>
        </a-row>

        <a-row :gutter="24">
          <a-col :span="24">
            <a-form-model-item label="备注" prop="remark">
              <a-textarea v-model="model.remark" placeholder="请输入备注信息" :rows="2" :maxLength="500" />
            </a-form-model-item>
          </a-col>
        </a-row>

        <!-- 调整预览 -->
        <a-alert
          v-if="model.adjustType && model.adjustQuantity"
          :message="adjustPreviewMessage"
          type="info"
          show-icon
          style="margin-bottom: 16px"
        />
      </a-form-model>
    </a-spin>
  </a-modal>
</template>

<script>
import { httpAction } from '@/api/manage'

export default {
  name: 'InventoryAdjustModal',
  components: {},
  data() {
    return {
      title: '库存调整',
      width: 600,
      visible: false,
      model: {},
      inventoryInfo: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      confirmLoading: false,
      validatorRules: {
        adjustType: [{ required: true, message: '请选择调整类型!', trigger: 'change' }],
        adjustQuantity: [
          { required: true, message: '请输入调整数量!', trigger: 'blur' },
          { type: 'number', min: 1, message: '调整数量必须大于0!', trigger: 'blur' },
        ],
        adjustReason: [
          { required: true, message: '请输入调整原因!', trigger: 'blur' },
          { min: 5, message: '调整原因至少5个字符!', trigger: 'blur' },
        ],
      },
      url: {
        adjust: '/wms/finished-goods/inventory/adjust',
      },
    }
  },
  computed: {
    maxAdjustQuantity() {
      if (this.model.adjustType === 2) {
        // 减少库存时，最大不能超过当前可用数量
        return this.inventoryInfo.availableQuantity || 0
      }
      return 9999 // 增加库存时的最大值
    },
    adjustPreviewMessage() {
      if (!this.model.adjustType || !this.model.adjustQuantity) {
        return ''
      }

      const currentQty = this.inventoryInfo.availableQuantity || 0
      const adjustQty = this.model.adjustQuantity || 0
      const afterQty = this.model.adjustType === 1 ? currentQty + adjustQty : currentQty - adjustQty
      const operation = this.model.adjustType === 1 ? '增加' : '减少'

      return `将${operation} ${adjustQty} 件，调整后可用数量为 ${afterQty} 件`
    },
  },
  created() {},
  methods: {
    show(record) {
      this.visible = true
      this.inventoryInfo = Object.assign({}, record)
      this.model = {
        inventoryId: record.id,
        adjustType: null,
        adjustQuantity: null,
        adjustReason: '',
        remark: '',
      }
    },
    handleAdjustTypeChange() {
      // 调整类型变更时重置数量
      this.model.adjustQuantity = null
    },
    calculateAfterQuantity() {
      // 计算调整后数量，用于预览
      // 这个方法主要是为了触发计算属性更新
    },
    handleOk() {
      const that = this
      // 触发表单验证
      this.$refs.form.validate((valid) => {
        if (valid) {
          that.confirmLoading = true
          let httpurl = ''
          let method = ''

          httpurl = that.url.adjust
          method = 'post'

          httpAction(httpurl, that.model, method)
            .then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
                that.handleCancel()
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
            })
        }
      })
    },
    handleCancel() {
      this.close()
    },
    close() {
      this.$emit('close')
      this.visible = false
      this.model = {}
      this.inventoryInfo = {}
      this.$refs.form.resetFields()
    },
  },
}
</script>
